#!/usr/bin/env python

import sys
import data
import pickle
import os.path
import logging
import glob

logger = logging.getLogger('allConverging.allconsuming.filedac')

def readObject(fileName):
    try:
        f = file(os.path.join('cache', fileName), 'r')
        o = pickle.load(f)
        f.close()
        return o
    except Exception, e:
        logger.error("Couldn't read from cache file " + fileName, exc_info = e)
        return None

def writeObject(o, fileName):
    fileName = os.path.join('cache', fileName)
    try:
        logger.debug('writing ' + fileName)
        if not os.path.exists('cache'):
            os.mkdir('cache', 0x755)
            
        f = file(fileName, 'wb')
        pickle.dump(o, f)
        f.close()
    except Exception, e:
        logger.error("Couldn't write to cache file " + fileName, exc_info = e)
        return

def sortFileListByDate(fileList):
    filesAndDates = [(os.path.getmtime(x), x) for x in fileList]
    filesAndDates.sort()
    return filesAndDates
    

def getUserList():
    '''Get a list of users from the file store. Returned as a list of
    (lastUpdateTime, userName) tuples''' 

    pathPrefix = os.path.join('cache', 'user.')
    pathPrefixLength = len(pathPrefix)
    userFiles = sortFileListByDate(glob.glob(pathPrefix + '*'))
        
    #return userFiles
    return [(x[0], x[1][pathPrefixLength:]) for x in userFiles]
    
def getItemList():
    '''Get a list of items from the file store. Returned as a list of
    (lastUpdateTime, itemNumber) tuples''' 

    pathPrefix = os.path.join('cache', 'item.')
    pathPrefixLength = len(pathPrefix)
    itemFiles = sortFileListByDate(glob.glob(pathPrefix + '*'))
    return [(x[0], x[1][pathPrefixLength:]) for x in itemFiles]
    #return itemFiles

def getUserConsumables(user):
    return readObject('user.' + user)

def doesUserExist(userName):
    userFileName = os.path.join('cache', 'user.')
    userFileName += userName
    return os.path.exists(userFileName)

def saveUserConsumables(userName, consumables):
    # for now, assume it's the consumables for one user, and all
    # of that user's consumables
    return writeObject(consumables, 'user.' + userName)

def saveItemConsumables(itemNumber, consumables):
    return writeObject(consumables, 'item.' + itemNumber)

def getItemConsumables(itemNumber):
    o = readObject('item.' + itemNumber)
    if o is not None:
        return o
    else:
        return None
